package com.it.sun.redismq.handler;

import cn.hutool.core.util.StrUtil;
import com.it.sun.redismq.annotation.MessageHandler;
import com.it.sun.redismq.annotation.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName com.it.sun.springboot.course.invoke.PubsubMessageInvoker
 * @Author sun
 * @Date 2021/1/28 10:21
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) xxxx  since 2021/1/28
 */
@MessageHandler(value = MessageListener.Mode.PUBSUB)
public class PubsubMessageHandler extends AbstractMessageHandler {

    public PubsubMessageHandler(RedisTemplate redisTemplate) {
        super (redisTemplate);
    }

    @Override
    public void invokeMessage(Method method) {
        Set<String> consumers = new HashSet<> ();
        MessageListener listener = method.getAnnotation (MessageListener.class);
        String channel = getChannel (listener);
        RedisConnection connection = getConnection ();
        connection.subscribe ((message, pattern) -> {
            Class<?> declaringClass = method.getDeclaringClass ();
            Object bean = applicationContext.getBean (declaringClass);
            byte[] body = message.getBody ();
            consumer (method, consumers, bean, body);
        }, channel.getBytes ());
    }

    private String getChannel(MessageListener annotation) {
        String value = annotation.value ();
        String channel = annotation.channel ();
        return StrUtil.isBlank (channel) ? value : channel;
    }
}
